package com.spsy.pay.config;

import com.spsy.pay.constant.LxConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.xml.transform.Source;

/**
 * @Author: Kyrie Irving
 * @Date: 2025/10/8 11:23
 * @Description:
 **/
@Configuration
public class LxConfig {
    @Bean
    public Queue queue(){
        return new Queue(LxConstant.LxQueue,true);
    }

    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange(LxConstant.LxExchange);
    }

    @Bean
    public Binding bindingBuilder(){
        return BindingBuilder.bind(this.queue()).to(this.directExchange()).with(LxConstant.LxRouting);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        //消息到达交换机但是到不了队列的时候会触发回退机制
        rabbitTemplate.setMandatory(true);

        rabbitTemplate.setConfirmCallback((correlationData,ack,cause)->{
            if (ack){
                System.out.println("消息成功到达交换机");
            }else {
                System.out.println("消息未能成功到达交换机，原因："+cause);
                System.out.println(correlationData != null ? correlationData.getId() : "未知");
            }
        });

        //回退机制
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            System.out.println("消息未能路由到队列");
            System.out.println("错误码："+returnedMessage.getReplyCode());
            System.out.println("原因："+returnedMessage.getReplyText());
            System.out.println("交换机："+returnedMessage.getExchange());
            System.out.println("路由键："+returnedMessage.getRoutingKey());
            System.out.println("消息："+new String(returnedMessage.getMessage().getBody()));
        });

        return rabbitTemplate;
    }
}
